package com.mitu.nio;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

public class NIOFileChannel {
    public static void main(String[] args) throws IOException {
        String hello = "Hello,World!";
        //创建一个输出流
        FileOutputStream fileOutputStream = new FileOutputStream("file01.txt");
        //通过文件输出流获取FileChannel
        FileChannel fileChannel = fileOutputStream.getChannel();

        //创建一个字节缓冲器
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //将字符串写到字节缓冲区中
        buffer.put(hello.getBytes(StandardCharsets.UTF_8));
        //转换缓冲区读写模式，从写模式转换为读模式
        buffer.flip();
        //将缓冲区中的数据写入到FileChannel中
        fileChannel.write(buffer);
        //关闭文件输出流!!!
        fileOutputStream.close();
    }
}
